/** 
  jtds-1.2.2.tar file (and its full path)  must be put into CLASSPATH
  environment variable to be able to use Java JDBC driver for Microsoft
  SQL Server 2000, 2005.
**/

import java.sql.*;
import java.io.*;

public class AccessMSSQLServer {

	Connection cnn;
	Statement  stmt;
	ResultSet  res;

	String url = "jdbc:jtds:sqlserver://starwolf.cs.csubak.edu:1433/PCMDATA",
		 user="PCMDATA", passwd="pcmcmg";

	public AccessMSSQLServer() {
	   try {
		// DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                Class.forName("net.sourceforge.jtds.jdbc.Driver");
		cnn = DriverManager.getConnection(url, user, passwd);
		stmt = cnn.createStatement();
	   } catch ( Exception e ) { e.printStackTrace(); System.exit(-1); }
	}

	public static void main(String argv[]) {
		AccessMSSQLServer ex3 = new AccessMSSQLServer(); // get connected, and create stmt.
		char c = ' ';
		String sql;

		while ( true ) {
			sql = ScreenIO.promptForString("\nEnter a SQL statement or Q/e to quite ... ");
			//if ( sql == null || sql.equals("") ) continue;
			try { c = sql.charAt(0); } catch (StringIndexOutOfBoundsException e) { continue;}
			if ( c == 'q' || c == 'Q' ) System.exit(0);
			ex3.executeSQL(sql);
			ScreenIO.displayResultSet(ex3.res);
		}
	}

	void executeSQL(String sql) {
	   try {
		if ( sql.charAt(sql.length() -1) == ';' ) sql = sql.substring(0, sql.length() -1);
		res = stmt.executeQuery(sql);
	   } catch (SQLException e) { System.err.println("\nError occured in executing SQL: \n\t" + sql + "\n"); }
	}


	protected void finalize() {
	   try {
		stmt.close();
		res.close();
		cnn.close();
	   } catch (SQLException e) {}
	   try { super.finalize(); } catch (Throwable e) {}
	}
}
